using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Pitoshka.Tools.Helpers;

namespace Pitoshka.Web.Controls
{
	[DefaultProperty("Text")]
	[ToolboxData("<{0}:AdZone runat=server></{0}:AdZone>")]
	public class AdZone : WebControl
	{
		[Category("Appearance")]
		[DefaultValue("adLocations")]
		public string ConfigKey
		{
			get
			{
				String s = (String)ViewState["ConfigKey"];
				return ((s == null) ? String.Empty : s);
			}
			set { ViewState["ConfigKey"] = value; }
		}

		[Category("Appearance")]
		[DefaultValue("")]
		public string Place
		{
			get
			{
				String s = (String)ViewState["Place"];
				return ((s == null) ? String.Empty : s);
			}
			set { ViewState["Place"] = value; }
		}


		protected string Url
		{
			get
			{
				return
					HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)
					+ HttpContext.Current.Request.RawUrl;
			}
		}

		private string GetZoneCode()
		{
			// Define url variables
			string appPath = HttpContext.Current.Request.ApplicationPath;
			if (appPath == "/")
				appPath = "";

			string fullPath = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + appPath;
			string reFullPath = fullPath.Replace(".", @"\.");



			// Get settings from XML File
			XmlDocument doc = CachedXmlDocuments.GetXmlDocument(this.ConfigKey);
			XmlNode locationNode = doc.DocumentElement.SelectSingleNode("AdLocation[@place='" + Place + "']");
			if (locationNode == null)
				return "";

			XmlNode htmlNode = locationNode.SelectSingleNode("HtmlBegin");
			string htmlBegin = (htmlNode == null) ? "" : htmlNode.InnerText;
			htmlNode = locationNode.SelectSingleNode("HtmlEnd");
			string htmlEnd = (htmlNode == null) ? "" : htmlNode.InnerText;
			XmlNodeList conditionNodes = locationNode.SelectNodes("Condition");



			// Try to find matching condition
			string retval = null;
			if (conditionNodes != null)
			{
				for (int i = 0; i < conditionNodes.Count; i++)
				{
					XmlNode conditionNode = conditionNodes[i];
					XmlNodeList regexNodes = conditionNode.SelectNodes("regex");
					foreach (XmlNode regexNode in regexNodes)
					{
						string pattern = regexNode.Attributes["value"].Value;
						pattern = pattern.Replace("~/", reFullPath + "/");
						if (System.Text.RegularExpressions.Regex.IsMatch(Url, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
						{
							retval = conditionNode.InnerText;
							break;
						}
					}
					if (retval != null)
						break;

				}
			}


			// If no appropriate condition found - then use default
			if (retval == null)
			{
				XmlNode defaultCondition = locationNode.SelectSingleNode("Default");
				if (defaultCondition == null)
					return "";
				retval = defaultCondition.InnerText;
			}

			retval = htmlBegin + retval + htmlEnd;
			return retval;
		}

		protected override void RenderContents(HtmlTextWriter output)
		{
			output.Write(GetZoneCode());
		}
	}
}